﻿using Mono.Cecil.Cil;
using Mono.Collections.Generic;

namespace il2lua.TypeSystem;

public class ILMethod : Role, IMethod
{
    public ILMethod(MethodKind methodKind, string name, IType parent, ObjectKind kind)
        : base(name, parent, kind)
    {
        MethodKind = methodKind;
        Variables = new List<IVariable>();
        Params = new List<IParam>();
        Instructions = new List<IInstruction>();
    }

    public MethodKind MethodKind { get; }
    public IParam SelfParam { get; set; }
    public IList<IVariable> Variables { get; }
    public IList<IParam> Params { get; }
    public IList<IInstruction> Instructions { get; }
    public IList<Instruction> RawInstructions { get; set; }

    public IParam GetParam(int index)
    {
        if (index == -1)
            return SelfParam;
        return Params[index];
    }

    public IVariable GetVariable(int index)
    {
        return Variables[index];
    }

    public override string ToString()
    {
        var paramStrs = Join(", ", Params.Select(x => x.Name));
        switch (MethodKind)
        {
            case MethodKind.StaticCtor:
                return $"__initialize__({paramStrs})";
            case MethodKind.Static:
                return $"{Parent.Name}.{Name}({paramStrs})";
            case MethodKind.Ctor:
                return $"{Parent.Name}:__ctor__({paramStrs})";
            case MethodKind.Instance:
                return $"{Parent.Name}:{Name}({paramStrs})";
        }
        return base.ToString();
    }
}
